<?php

namespace App\Store\Controllers\Member;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Member\SiteMemberLv;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Member\CommonMember;
use Illuminate\Support\Facades\DB;

/**
 * 会员积分信息
 */
class MemberPointsController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = MemberPointsChangelog::getList($request);
        foreach($list['list'] as &$val){
            $val['lv_name'] = isset($val['memberinfo']['member_lv']) ?SiteMemberLv::where(['id' => $val['memberinfo']['member_lv']])->value('lv_name'):'';
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 会员增加积分
     */
    public function memberaddpoints(Request $request)
    {
        $mem_id = intval($request->mem_id);
        $points_num = intval($request->points_num);
        $remark = strval($request->remark);
        if($points_num<=0){
            return response()->json(['code' => '001', 'msg' => '添加积分需大于0']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = Member::where(['id' => $mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $data=[
            'cp_id'=>$cp_id,
            'mem_id'=>$mem_id,
            'type'=>21,
            'store_id'=>$info->store_id,
            'change_val'=>$points_num,
            'change_before'=>$info->points_current,
            'change_after'=>$info->points_current+$points_num,
            'sales_account_id'=>$accountinfo['id'],
            'loginfo'=>json_encode(['title'=>'手动添加']),
            'create_account_id' => $accountinfo['id'],
            'update_account_id' => $accountinfo['id'],
            'create_account_real_name' => $accountinfo['real_name'],
            'update_account_real_name' => $accountinfo['real_name'],
            'create_at' => time(),
            'update_at' => time(),
            'remark'=>$remark,
        ];
        DB::beginTransaction();
        try {
            MemberPointsChangelog::create($data);
            Member::where(['id' => $mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
            'points_current'=> DB::raw('points_current + ' . $points_num),
            'points_total'=> DB::raw('points_total + ' . $points_num),
            ]);

            CommonMember::checkMemLv($info->id);//会员升级

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '积分增加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '积分增加成功']);
    }
    /**
     * 下载模板
     */
    public function dodownload(Request $request)
    {
        $row = [['姓名','会员手机号', '增加积分', '备注']];
        $options = [

        ];
        $datawith = [
            'A' => '25',
            'B' => '25',
            'C' => '25',
            'D' => '40',
        ];
        $filename = '积分明细信息导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }
    /**
     * 导入
     */
    public function doimport(Request $request)
    {

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];

            $ins_data = [];
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    if(count($val)!=4){
                        return response()->json(['code' => '001', 'msg' =>'导入数据格式错误']);
                    }
                    continue;
                }
                $info = Member::where(['mobile' => $val[1], 'cp_id' => $cp_id, 'is_del' => 1])->first();
                if (!$info) {
                    return response()->json(['code' => '001', 'msg' => '存在无效会员'.$val[1]]);
                }
                if(intval($val[2])<=0){

                    return response()->json(['code' => '001', 'msg' => '无效积分值'.$val[2]]);
                }
                $valdata = [
                    'cp_id'=>$cp_id,
                    'mem_id'=>$info->id,
                    'type'=>21,
                    'store_id'=>$info->store_id,
                    'change_val'=>intval($val[2]),
                    'change_before'=>$info->points_current,
                    'change_after'=>$info->points_current+intval($val[2]),
                    'sales_account_id'=>$accountinfo['id'],
                    'loginfo'=>json_encode(['title'=>'手动添加']),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark'=>$val[3]?strval($val[3]):'',
                ];
                $ins_data[]=$valdata;
            }

            DB::beginTransaction();
            try {
                foreach($ins_data as $val){
                    Member::where(['id' => $val['mem_id'], 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_current'=> DB::raw('points_current + ' . $val['change_val']),
                        'points_total'=> DB::raw('points_total + ' . $val['change_val']),
                        ]);
                        CommonMember::checkMemLv($val['mem_id']);//会员升级
                }
                MemberPointsChangelog::insert($ins_data);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '积分增加失败' . $e->getMessage()]);
            }

            return response()->json(['code' => '000', 'msg' => '数据导入成功']);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        //isgetall=1;
        //积分类型，1注册赠送，2充值赠送，3购物赠送，4旧料回收赠送，11积分兑换，21手动添加，22年底清零
        $type=[
            '1'=>'注册赠送',
            '2'=>'充值赠送',
            '3'=>'购物赠送',
            '4'=>'旧料回收赠送',
            '5'=>'积分转预存',
            '6'=>'会员签到',
            '11'=>'积分兑换',
            '21'=>'手动添加',
            '22'=>'年底清零',
            '23'=>'积分红冲',
            '24'=>'信息变更'
        ];
        $list = MemberPointsChangelog::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['start_store'=>'积分明细列表'],
            [
                'store_name' => '门店名称',
                'real_name' => '会员名称',
                'mobile' => '会员电话',
                'lv_name' => '会员等级',
                'type'=>'类型',
                'logtitle' => '兑换物品',
                'change_val'=>'积分变动',
                'sales_account_name' => '业务员',
                'remark' => '备注',
                'create_account_real_name'=>'创建人',
                'create_at'=>'创建时间',
                'update_account_real_name'=>'更新人',
                'update_at'=>'更新时间',
            ]
        ];
        foreach ($list as $val) {
            $loginfo=json_decode($val['loginfo'],true);
            $exceldata[] = [
                'store_name'=>$val['storeinfo']['store_name']??'',
                'real_name'=>$val['memberinfo']['real_name']??'',
                'mobile'=>$val['memberinfo']['mobile']??'',
                'lv_name'=>  isset($val['memberinfo']['member_lv']) ?SiteMemberLv::where(['id' => $val['memberinfo']['member_lv']])->value('lv_name'):'',
                'type'=>$type[$val['type']],
                'logtitle'=>isset($loginfo['title'])?$loginfo['title']:'',
                'change_val'=>$val['change_val'],
                'sales_account_name'=>$val['accountinfo']?$val['accountinfo']['real_name']:'',
                'remark'=>$val['remark'],
                'create_account_real_name'=>$val['create_account_real_name'],
                'create_at'=>date('Y-m-d H:i:s',$val['create_at']),
                'update_account_real_name'=>$val['update_account_real_name'],
                'update_at'=>date('Y-m-d H:i:s',$val['update_at'])
            ];
        }

        $filename = '积分明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }
}
